package com.ticket.sass.provider.util;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

/**
 * @author ywb
 * @date 2022-11-24 11:34
 */
@Slf4j
public class CompareUtil<T> {
    
    // 比较的旧集合
    List<T> oldList;
    
    // 比较的新集合
    List<T> newList;
    
    // 初始化添加和删除
    private List<T> addList;
    private List<T> delList;
    // 未改变
    private List<T> commonList;
    
    public CompareUtil(List<T> oldList, List<T> newList) {
        this.oldList = Optional.ofNullable(oldList).orElse(new ArrayList<>());
        this.newList = Optional.ofNullable(newList).orElse(new ArrayList<>());
        // 初始化比较信息
        this.initCompare();
    }
    
    
    private void initCompare() {
        commonList = new ArrayList<>();
        Iterator<T> it = newList.iterator();
        while(it.hasNext()){
            T i = it.next();
            if(oldList.contains(i)){
                commonList.add(i);
                oldList.remove(i);
                it.remove();
            }
        }
        addList = newList;
        delList = oldList;
    }
    
    public List<T> getInsert() {
        return this.addList;
    }
    
    public List<T> getDel() {
        return this.delList;
    }
    
    public List<T> getCommonList() {
        return commonList;
    }
    
    public Boolean isInsert(){
        return CollectionUtil.isNotEmpty(this.addList);
    }
    
    public Boolean isDel(){
        return CollectionUtil.isNotEmpty(this.delList);
    }
    
    public Boolean isCommon(){
        return CollectionUtil.isNotEmpty(this.commonList);
    }
    
    /**
     * 检查旧集合和新集合是否完全相同
     *
     * @return 如果两个集合完全相同返回 true，否则返回 false
     */
    public Boolean isSame() {
        return addList.isEmpty() && delList.isEmpty();
    }
    
    
    @Override
    public String toString() {
        return "CompareUtil{" +
            "oldList=" + oldList +
            ", newList=" + newList +
            ", addList=" + addList +
            ", delList=" + delList +
            ", commonList=" + commonList +
            '}';
    }
}
